// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command;
const $ = db.command.aggregate;

// 云函数入口函数
exports.main = async (event, context) => {
  //批量减库存
  try{
    for(var i=0;i<event.goods.length;i++){
      var goods_tm = event.goods[i].bz;
      var goods_num = event.goods[i].goods_num;
      var goods_ysl =  await db.collection('commodity').aggregate()
        .match({
          user_id:event.user_id,
        })
        .project({
          user_id:event.user_id,
          goods: $.filter({
            input: '$goods',
            as: 'item',
            cond: $.gte([$.indexOfBytes(['$$item.bz',goods_tm]), 0])
          })
        })
        .end()
        goods_ysl = goods_ysl.list[0].goods[0].goods_num;
        var goods_sl = parseInt(parseInt(goods_ysl) - parseInt(goods_num));
        await db.collection('commodity').where({
          user_id: event.user_id,
          //根据商品条码进行编辑
          goods:{
            bz:goods_tm,
          }
        }).update({
          data: {
            'goods.$.goods_num':goods_sl,
          }
        })
    }
  }catch(e){
    console.log("批量减库存出现异常:" + e)
  }
  return await db.collection('pay_count').add({
    data: event
  })
}